import { defineConfig, loadEnv, type PluginOption, normalizePath } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from "path";
import AutoImport from "unplugin-auto-import/vite"
import Components from 'unplugin-vue-components/vite'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import { ElementPlusResolver, AntDesignVueResolver } from 'unplugin-vue-components/resolvers'
import postcsspxtoviewport from "postcss-px-to-viewport-8-plugin"
import vueJsx from '@vitejs/plugin-vue-jsx'
import { visualizer } from 'rollup-plugin-visualizer'
import Icons from 'unplugin-icons/vite';
import IconsResolver from 'unplugin-icons/resolver';
import vueSetupExtend from 'vite-plugin-vue-setup-extend'
import viteCompression from 'vite-plugin-compression';
import electron from "vite-plugin-electron"
import electronRenderer from "vite-plugin-electron-renderer"
import polyfillExports from "vite-plugin-electron-renderer"
// import autoprefixer from 'autoprefixer'
// const variablePath = normalizePath(path.resolve('./src/styles/global.scss'));
const autoImport = AutoImport({
  include: [
    /\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
    /\.vue$/, /\.vue\?vue/, // .vue
  ],
  imports: ["vue", "vue-router", "pinia", "@vueuse/core"],
  dts: "/config/auto-import.d.ts",
  resolvers: [ElementPlusResolver(), IconsResolver({
    prefix: 'Icon'
  }), AntDesignVueResolver()],
  eslintrc: { enabled: true },
})
const components = Components({
  dts: "/config/components.d.ts",
  extensions: ['vue', 'jsx', 'tsx', 'ts', 'js'],
  resolvers: [ElementPlusResolver(),
  IconsResolver({
    enabledCollections: ['ep']
  }), AntDesignVueResolver({
    importStyle: true,
    resolveIcons: true
  })
  ],
})
const svgIcon = createSvgIconsPlugin({
  iconDirs: [path.resolve(__dirname, 'src/assets/icons/')],
  symbolId: 'icon-[name]'
})
const pxtovw = postcsspxtoviewport({
  unitToConvert: 'px', // 要转化的单位
  viewportWidth: 320, // UI设计稿的宽度
})
export default defineConfig(({ command, mode }) => {
  loadEnv(mode, process.cwd());
  return {
    base: mode == 'development' ? '' : './',
    envPrefix: 'VITE_',
    envDir: path.resolve(__dirname, 'env'),
    plugins: [
      vue(),
      // electron([{
      //   entry: "electron/electron-main/index.ts", // 主进程文件
      // },
      // {
      //   entry: 'electron/electron-preload/preload.ts'
      // }
      // ]),//开启选项为双端调试
      electronRenderer(),
      polyfillExports(),
      viteCompression({
        verbose: true, // 默认即可
        disable: false, //开启压缩(不禁用)，默认即可
        deleteOriginFile: false, //删除源文件
        threshold: 10240, //压缩前最小文件大小
        algorithm: 'gzip', //压缩算法
        ext: '.gz', //文件类型
      }),
      // visualizer({
      //   open:true,  //注意这里要设置为true，否则无效
      //   gzipSize:true,
      //   brotliSize:true
      // }),
      autoImport,
      components,
      svgIcon,
      vueSetupExtend(),
      Icons({
        autoInstall: true
      }),
      vueJsx(),
      pxtovw,
      visualizer({
        open: true,
        gzipSize: true,
        brotliSize: true,
        emitFile: true,
        filename: 'stats.html'
      }) as unknown
    ],
    resolve: {
      alias: {
        "@": path.resolve(__dirname, "./src"),
        '~': path.resolve(__dirname, './'),
      }
    },
    define: {
      'process.env': {}
    },
    server: {
      open: '/',
      host: '0.0.0.0',
      https: false,
      proxy: {           //代理
        // '/': {
        // target: process.env.VITE_PROXY_URL,    //请求的url，例后端给的地址
        // changeOrigin: true,        //当进行代理时，Host 头部的源默认会保持原状；你可以设置 changeOrigin 为 true 来覆盖这种行为；变成target对应得地址
        // secure: false,             // 关闭SSL证书校验
        // rewrite: path => {         //重定地址，比如：把以/aaa开头的地址换成''
        //   return path.replace(/^\/aaaa/, '');
        // },
        // },
      },
    },
    build: {
      minify: "terser", // 必须开启：使用 terserOptions 才有效果
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true,
        },
      },
      outDir: mode,
      rollupOptions: {
        output: {
          manualChunks(id) {
            // 文件路径 id
            const chunkArray = ['dayjs', '@element-plus', 'vue', 'vue-router'];

            if (chunkArray.find((chunk) => id.includes(`node_modules/${chunk}/`))) {
              return id.toString().split('node_modules/')[1].split('/')[0].toString();
            }
          },
          chunkFileNames: (chunkInfo) => {
            const facadeModuleId = chunkInfo.facadeModuleId ? chunkInfo.facadeModuleId.split('/') : [];
            const fileName = facadeModuleId[facadeModuleId.length - 2] || '[name]';
            return `js/${fileName}/[name].[hash].js`;
          }
        }
      }
    },
    css: {
      // preprocessorOptions: {
      //   scss: {
      //     additionalData: `@import "${variablePath}";`
      //   }
      // },
      // postcss: {
      //   plugins: [
      //     autoprefixer({
      //       // 指定目标浏览器
      //       overrideBrowserslist: ['> 1%', 'last 2 versions']
      //     })
      //   ]
      // }
    }
  }
})
